package clw.toy;

import java.util.List;
import java.util.Map;

/**
 * @author chengliwei
 */
public class ToyClass implements Functionable {
    String name;
    ToyClass superClass;
    protected Map<String, Function> methods;

    public ToyClass(String name, ToyClass superClass, Map<String, Function> methods) {
        this.name = name;
        this.superClass = superClass;
        this.methods = methods;
    }

    @Override
    public int arity() {
        Function initializer = findMethod("init");
        if (initializer == null) return 0;
        return initializer.arity();
    }

    @Override
    public Object call(Interpreter interpreter, List<Object> arguments) {
        ToyInstance instance = new ToyInstance(this);
        Function initializer = findMethod("init");
        if (initializer != null) {
            initializer.bind(instance).call(interpreter, arguments);
        }
        return instance;
    }

    public Function findMethod(String name) {
        if (methods.containsKey(name)) {
            return methods.get(name);
        }

        if (superClass != null) {
            return superClass.findMethod(name);
        }
        return null;
    }
}
